<?php
namespace App\Admin\Controllers\SalesReport;

use App\Models\Basics\SysCountry;
use App\Models\Basics\SysPlat;
use App\Models\Product\ProductClassify;
use App\Models\SalesReport\MonthlyCTarget;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\StreamedResponse;
use App\Importer\SalesReport\MCTImporter;
class MonthlyCTargetController extends AdminController{

    protected $title = '品类月销量和月目标-上传';

    public function upload(Content $content)
    {
        return $content
            ->title($this->title())
            ->description($this->description['index'] ?? trans('admin.list'))
            ->body(view('sales-report.monthly-ct-upload.index'));
    }

    public function doUpload(Request $request){

        $platId = $request->get('plat_id');
        if (!$platId) {
            admin_toastr('平台异常！','error');
            return back()->withInput();
        }

        $file = $request->file('source_file');
        if ($file->isValid()) {
            $re = $this->_importFile($file,$platId);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importFile(UploadedFile $file,$platId){
        try{
            $data = Excel::toArray(new MCTImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            DB::beginTransaction();
            $errors = [];
            $count = 1;
            foreach($data as $v){
                $count++;
                $_country = $v[0] ? trim($v[0]) : '';
                $classify = $v[1] ? trim($v[1]) : '';
                if(!$_country || !$classify){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                $j = 2;
                for($i = 0; $i < MonthlyCTarget::E_NUM; $i++){
                    ${'estimateVolume'.$i} = is_null($v[$j]) ? null : trim($v[$j]);
                    $j++;
                }
                $country = strtoupper($_country);
                $countryId = SysCountry::getIdByCountry($country);
                if(!$countryId){
                    $errors[$count] = $_country.'系统不存在';
                    continue;
                }
                $classifyId = ProductClassify::getIdByTitle($classify);
                if(!$classifyId){
                    $errors[$count] = '品类不存在';
                    continue;
                }
                $item1 = [
                    'plat_id' => $platId,
                    'monthly' => MonthlyCTarget::START_DATE,
                    'country_id' => $countryId,
                    'classify_id' => $classifyId,
                ];
                $item2 = [];
                for($i = 0;$i < MonthlyCTarget::E_NUM;$i++){
                    if(!is_null(${'estimateVolume'.$i})){
                        $item2['estimate_volume'.$i] = ${'estimateVolume'.$i};
                    }
                }
                MonthlyCTarget::query()->updateOrCreate($item1,$item2);
            }
            DB::commit();
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            DB::rollBack();
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }

    public function download(){
        $title1 = ['平台','站点','国家','季节性','品类','销售'];
        $title2 = [];
        $startTime = strtotime(MonthlyCTarget::START_DATE);
        for($i = 0; $i < MonthlyCTarget::E_NUM; $i++){
            $thisTime = strtotime("midnight first day of +$i month",$startTime);
            $title2[] = date("y/m",$thisTime).'目标值';
        }
        $head = array_merge($title1,$title2);
        $response = new StreamedResponse(null, 200, [
            'Content-Type'        => 'text/csv;charset=utf-8',
            'Content-Disposition' => 'attachment;filename="品类月目标.csv"',
        ]);
        $query = MonthlyCTarget::query()->where('monthly',MonthlyCTarget::START_DATE);
        $response->setCallback(function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->orderBy('id','DESC')->chunk(100, function ($re) use ($fp){
                $data = MonthlyCTarget::getData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
            fclose($fp);
        });
        $response->send();
        exit(0);
    }
}
